package com.rzico.sbl.picture

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.engine.CropFileEngine
import com.luck.picture.lib.utils.ActivityCompatHelper
import com.xinnuo.common.extend.condition
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine

/**
 * Glide相册裁剪引擎
 */
class PictureCropEngine : CropFileEngine {

    override fun onStartCrop(
        fragment: Fragment,
        srcUri: Uri,
        destinationUri: Uri,
        dataSource: ArrayList<String>,
        requestCode: Int
    ) {
        UCrop.of(srcUri, destinationUri, dataSource)
            .apply {
                withOptions(
                    fragment
                        .requireContext()
                        .buildCropOption()
                )

                setImageEngine(object : UCropImageEngine {

                    override fun loadImage(context: Context, url: String, imageView: ImageView) {
                        ActivityCompatHelper
                            .assertValidRequest(context)
                            .condition {
                                Glide.with(context)
                                    .load(url)
                                    .override(180, 180)
                                    .into(imageView)
                            }
                    }

                    override fun loadImage(
                        context: Context,
                        url: Uri,
                        maxWidth: Int,
                        maxHeight: Int,
                        call: UCropImageEngine.OnCallbackListener<Bitmap>
                    ) {
                        Glide.with(context)
                            .asBitmap()
                            .load(url)
                            .override(maxWidth, maxHeight)
                            .into(object : CustomTarget<Bitmap?>() {
                                override fun onResourceReady(
                                    resource: Bitmap,
                                    transition: Transition<in Bitmap?>?
                                ) {
                                    call.onCall(resource)
                                }

                                override fun onLoadCleared(placeholder: Drawable?) {
                                    call.onCall(null)
                                }
                            })
                    }

                })

                start(fragment.requireActivity(), fragment, requestCode)
            }
    }

}